const { init } = require('./../../wxCloudClientSDK.umd.js')
// 指定云开发环境 ID
wx.cloud.init({
  env: "cloud1-9gel6ndh8e555155", // 当前的云开发环境 ID
});
const client = init(wx.cloud);

Page({
  data: {
    userPoints: 1280,
    showRulesPopup: false,
    pointsRules: [
      {
        id: 1,
        title: '签到规则',
        description: '1、每笔积分从获取时间开始计算，积分不限有效期。'
      },
      {
        id: 2,
        title: '消费规则',
        description: '2、会员积分兑换礼品清单详见微商城，兑换礼品以最终收到的实物为准。'
      },
      {
        id: 3,
        title: '积分有效期',
        description: '3、会员在获取积分后，可根据分值在微商城中兑换相应礼品，兑换成功后将从会员账号积分余额中扣减相应积分分值。'
      },
      {
        id: 4,
        title: '售后服务',
        description: '若收到产品有质量问题，请自收到产品之日起7日内与机构工作人员联系，过期不做处理。'
      },
      {
        id: 5,
        title: '备注信息',
        description: '注：本着为会员提供更优质服务为宗旨，武汉尚小镜内镜诊疗平台将会不时的对会员规则进行修改与完善。如果是涉及会员权益的细则修改，武汉尚小镜内镜诊疗平台会以广告通知、店内告示或在武汉尚小镜内镜诊疗平台官网上提前做出通告。'
      },
      {
        id: 6,
        title: '版权信息',
        description: '本规则最终解释权归武汉尚小镜内镜诊疗平台所有。'
      }
    ],
    currentTab: 1, // 当前选中标签
    featuredGoods: [],
    exchangeableGoods: [],

    categories: [
      { id: 1, name: '精选商品' },
      { id: 2, name: '我可兑换' },
    ],
    currentCategory: 1,
    page: 1,  // 当前页码
    pageSize: 5, // 每页数据量
    loading: false,  // 是否正在加载
    noMoreData: false,  // 是否没有更多数据
  },

  onLoad: function() {

    this.querySelectedGoods();
    
  },

  querySelectedGoods() {

    if (this.data.loading || this.data.noMoreData) return;  // 防止重复加载

    this.setData({ loading: true });

    this.loadData(this.data.page, this.data.pageSize);

  },

  loadData(page, pageSize) {
      // 获取积分的精选商品
      client.models.goods_info.list({
        filter: {
          where: {
          $and: [{
            category: {
              $eq: 'selectedGoods'
            },
          },
        ],
          }
        },
        pageSize: pageSize,
        pageNumber: page,
        getCount: true
      }).then(res => {
      console.log("goods_info: " + res.data.records);
      if (res.data?.records?.length > 0) {
        this.parseSelectedGoods(res.data.records);

        this.setData({
          page: this.data.page + 1,  // 页码加1
        });
      } else {
        this.setData({
          noMoreData: true,     // 没有更多数据
        });
      }

      this.setData({ loading: false });
      
    }).catch(res => {
      console.log("goods_info err: " + res)
    });
  },

  parseSelectedGoods(data) {
    const parsedData = data.map(item => {
      return {
        id: item._id,
        name: item.goodsName,
        desc: item.description,
        points: item.price,
        imageUrl: item.thumbnailUrl,
      };
    });

    this.setData({
      featuredGoods: this.data.featuredGoods.concat(parsedData)
    });

  },

  toGoodsDetail(event) {
    const id = event.currentTarget.dataset.param1;
    wx.navigateTo({
      url: '/page/goodsdetail/index?param1=' + id,
    });
  },

  // 监听页面滚动到底部
  onReachBottom() {
    if (this.data.currentTab === 1) {
      this.querySelectedGoods();  // 加载精选商品下一页
    } else {
      this.queryExchangeGoods();  // 加载我可兑换下一页
    }

    
  },

  // 切换商品分类
  switchTab(e) {
    const tabIndex = parseInt(e.currentTarget.dataset.tab);
    this.setData({
      currentTab: tabIndex,
      loading: false,  // 是否正在加载
      noMoreData: false,  // 是否没有更多数据
      page: 1,
      pageSize: 5
    });

    if (tabIndex === 2) {
      this.queryExchangeGoods();
    }
  },

  queryExchangeGoods() {

    if (this.data.loading || this.data.noMoreData) return;  // 防止重复加载

    this.setData({ loading: true });

    this.loadExchangeGoodsData(this.data.page, this.data.pageSize);

  },

  loadExchangeGoodsData(page, pageSize) {
      // 获取积分的精选商品
      client.models.goods_info.list({
        filter: {
          where: {
          $and: [{
            category: {
              $eq: 'selectedGoods'
            },
          }, {
            price: {
              $lte: 2000
            }
          }
        ],
          }
        },
        pageSize: pageSize,
        pageNumber: page,
        getCount: true
      }).then(res => {
        console.log("exchange goods_info: " + res.data.records);
        if (res.data?.records?.length > 0) {
          this.parseExchangeGoods(res.data.records);

          this.setData({
            page: this.data.page + 1,  // 页码加1
          });
        } else {
          this.setData({
            noMoreData: true,   // 没有更多数据
          });
        }
        
        this.setData({ loading: false });

    }).catch(res => {
      console.log("goods_info err: " + res)
    });
  },

  parseExchangeGoods(data) {
    const parsedData = data.map(item => {
      return {
        id: item._id,
        name: item.goodsName,
        desc: item.description,
        points: item.price,
        url: item.thumbnailUrl,
      };
    });

    this.setData({
      exchangeableGoods: this.data.exchangeableGoods.concat(parsedData)
    });
  },

  showRules() {
    this.setData({
      showRulesPopup: true
    });
  },

  hideRules() {
    this.setData({
      showRulesPopup: false
    });
  },

  completeTask(e) {
    const taskId = e.currentTarget.dataset.id;
    const tasks = this.data.dailyTasks.map(task => {
      if (task.id === taskId && !task.completed) {
        // 完成任务逻辑
        wx.showToast({
          title: '获得' + task.points + '积分',
          icon: 'success'
        });
        return { ...task, completed: true };
      }
      return task;
    });
    this.setData({
      dailyTasks: tasks
    });
  },

  navigateToRecommend() {
    wx.navigateTo({
      url: '/pages/recommend/index'
    });
  },

  navigateToExchange() {//点击积分页面明细
    wx.navigateTo({
      url: '/page/mypoints/index'
    });
  },


  onCategoryChange(e) {
    const id = parseInt(e.currentTarget.dataset.id);
    this.setData({
      currentCategory: id,
      currentTab: id,
      loading: false,  // 是否正在加载
      noMoreData: false,  // 是否没有更多数据
      page: 1,
      pageSize: 5
    })

    if (id === 2) {
      this.setData({
        exchangeableGoods: []
      });
      this.queryExchangeGoods();
    } else {
      this.setData({
        featuredGoods: []
      });
      this.querySelectedGoods();
    }
  },

  navigateToTask: function() {
    wx.navigateTo({
      url: '/page/recommend/index',
    })
  },

});